using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;

namespace DE.Sdc.SharePoint.Common.Deployment
{
    [Serializable]
    [XmlType(AnonymousType = true, Namespace = "http://sdc/2009/07/Deployment/1.0/ContentStructure")]
    [XmlRoot(Namespace = "http://sdc/2009/07/Deployment/1.0/ContentStructure", IsNullable = false)]
    public class File
    {
        /// <remarks/>
        public Item Item { get; set; }

        /// <remarks/>
        [XmlArrayItem("WebPart")]
        public List<WebPart> WebParts { get; set; }

        /// <remarks/>
        [XmlAttribute]
        public FileActionType FileAction { get; set; }

        /// <remarks/>
        [XmlAttribute]
        public bool IsDefault { get; set; }

        /// <remarks/>
        [XmlAttribute]
        public bool RemoveAllWebParts { get; set; }

        /// <remarks/>
        [XmlAttribute]
        public bool OverwriteFileTitleWithItemTitle { get; set; }

        /// <summary>
        /// Modifies the properties for a file
        /// </summary>
        /// <param name="itemDefinition">Xml object for a file</param>
        /// <param name="file">The file which properties should updated</param>
        protected internal static void ModifyFile(Item itemDefinition, SPFile file)
        {
            Trace.WriteLine("Try to modify file '" + itemDefinition.Title + "' with url '" + itemDefinition.AbsoluteUrl + "'.", "ContentStructureImporter:ModifyFile");

            if (itemDefinition.File != null && itemDefinition.File.IsDefault)
            {
                try
                {
                    Trace.WriteLine("Try to modify file '" + itemDefinition.Title + "' with url '" + itemDefinition.AbsoluteUrl + "'.", "ContentStructureImporter:ModifyFile");
                    PublishingWeb web = PublishingWeb.GetPublishingWeb(file.ParentFolder.ParentWeb);
                    if (web.DefaultPage == null || web.DefaultPage.Url != file.Url)
                    {
                        web.DefaultPage = file;
                        web.Update();
                    }
                    Trace.WriteLine("File '" + itemDefinition.Title + "' with url '" + itemDefinition.AbsoluteUrl + "' modified.", "ContentStructureImporter:ModifyFile");

                }
                catch (TypeLoadException ex)
                {
                    Trace.WriteLine("Error on modifing file '" + itemDefinition.Title + "' with url '" + itemDefinition.AbsoluteUrl + "'.", "ContentStructureImporter:ModifyFile");
                    Trace.WriteLine(ex.Message, "ContentStructureModifier:ModifyFile");
                }
            }

            Trace.WriteLine("File '" + itemDefinition.Title + "' with url '" + itemDefinition.AbsoluteUrl + "' modified.", "ContentStructureImporter:ModifyFile");
        }
    }
}